package com.le.tester.imooc.masterJUC.lock.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * 描述：原子数组
 */
public class AtomicArrayDemo1 {
    public static void main(String[] args) {
        AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(1000);
        Thread[] threadsInc = new Thread[100];
        Thread[] threadsDec = new Thread[100];

        Increment increment = new Increment(atomicIntegerArray);
        Decrement decrement = new Decrement(atomicIntegerArray);

        for (int i = 0; i < 100; i++) {
            //这边只是定义了数组，并没有使用new Thread
            threadsDec[i] = new Thread(decrement);
            threadsInc[i] = new Thread(increment);
            threadsInc[i].start();
            threadsDec[i].start();
        }
        for (int i = 0; i < 100; i++) {
            try {
                threadsDec[i].join();
                threadsInc[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            System.out.println(atomicIntegerArray.get(i));
            if (atomicIntegerArray.get(i) != 0) {
                System.out.println("运行出错," + atomicIntegerArray.get(i));
            }
        }
        System.out.println("运行结束");
    }


}

class Decrement implements Runnable {
    private AtomicIntegerArray array;

    public Decrement(AtomicIntegerArray atomicIntegerArray) {
        this.array = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < array.length(); i++) {
            //传入数据的下标
            array.getAndDecrement(i);
        }

    }
}

class Increment implements Runnable {
    private AtomicIntegerArray array;

    public Increment(AtomicIntegerArray array) {
        this.array = array;
    }

    @Override
    public void run() {
        for (int i = 0; i < array.length(); i++) {
            //i指的是数组的下标
            array.getAndIncrement(i);
        }
    }
}
